package com.codingxyz.simple.lock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

class MyCache{

    private volatile Map<String,Object> map = new HashMap<>();

    private ReentrantReadWriteLock rmlock = new ReentrantReadWriteLock();
    public void put(String key,String val){

        rmlock.writeLock().lock();
        System.out.println(Thread.currentThread().getName() + " \t 正在写入 : "+key);
        try{
            TimeUnit.MICROSECONDS.sleep(300);
            map.put(key,val);
            System.out.println(Thread.currentThread().getName() + " \t 写入完成 : "+key);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            rmlock.writeLock().unlock();
        }

    }


    public void get(String key){

        rmlock.readLock().lock();
        System.out.println(Thread.currentThread().getName() + " \t 读取 : "+key);
        try{
            TimeUnit.MICROSECONDS.sleep(300);
            Object result = map.get(key);
            System.out.println(Thread.currentThread().getName() + " \t 读取完成 : "+result);
        }catch (Exception e){e.printStackTrace();}finally {
            rmlock.readLock().unlock();
        }

    }
}

/**
 * 多线程同时读一个资源类没问题，所以为了满足并发要求，读取共享资源应该可以同时进行
 * 但是如果有一个线程想去写共享资源，就不应该再有其他线程可以对该资源进行读或者写
 * 小总结：读-读能共存
 *        读-写不能共存
 *        写-写不能共存
 *
 * 写操作：原子+独占 整个过程必须是一个完整的通统一体，中间不允许被打断
 */
public class ReadWriteLockDemo {

    public static void main(String[] args) {

        MyCache cache = new MyCache();
        for (int i = 0; i < 5; i++) {
            final int tmpInt = i;
            new Thread(()->{
                cache.put(tmpInt+"",tmpInt+"");
            },String.valueOf(i)).start();
        }

        for (int i = 0; i < 6; i++) {
            final int tmpInt = i;
            new Thread(()->{
                cache.get(tmpInt+"");
            },String.valueOf(i)).start();
        }
    }
}
